<template>
	<!-- <view class="" v-if="stockData['f43']"> -->
	<view class="">
		<view class="cell">
			<view class="label">代码</view>
			<view class="flex align-center">
				<text>{{stockData?.['f58']}}</text>
				<text>[{{stockData?.['f57']}}]</text>
			</view>
		</view>

		<view class="cell">
			<view class="label">现价</view>
			<view class="text-orange">
				{{stockData?.['f43']/100||'--'}}
			</view>
		</view>

		<!-- 开启委托可改买入价格 -->
		<view class="cell" v-if="sysConfigObj?.is_weituo==1">
			<view class="label">买入价格</view>
			<view class="text-orange">
				<tui-numberbox disabled :width="400" :value="price" @change="changePrice" :step="0.01"
					:min="stockData?.['f52']/100" :max="stockData?.['f51']/100"></tui-numberbox>
			</view>
		</view>
		<view class="cell" v-else>
			<view class="label">买入价格</view>
			<view class="text-orange">
				{{stockData?.['f43']/100||'--'}}
			</view>
		</view>
		<view class="cell">
			<view class="label">涨跌停</view>
			<view class="flex justify-between flex-sub  padding-right">
				<view class="text-green">跌停：{{stockData?.['f52']/100||'--'}}</view>
				<view class="text-red">涨停：{{stockData?.['f51']/100||'--'}}</view>
			</view>
		</view>


		<view class="cell" v-if="is_pz==0">
			<view class="label">仓位</view>
			<view class="flex flex-wrap" style="align-items: center;">
				<text style="font-size: 24rpx;" @click="chooseNum(item.num,'turnover')" class="tag"
					:class="turnover==item.num?'active':''" v-for="(item,index) in turnovers"
					:key="index">{{item.name}}</text>
			</view>
		</view>
		<view class="cell" v-if="is_pz==1">
			<view class="label">倍数</view>
			<view class="flex flex-wrap" style="align-items: center;">
				<text style="font-size: 24rpx;" @click="choosemuilty(item,'lever')" class="tag"
					:class="level==item?'active':''" v-for="(item,index) in levers" :key="index">{{item}}</text>
			</view>
		</view>
		<view class="cell">
			<view class="label">买入手数</view>
			<tui-numberbox :width="160" :value="handNum" @change="changeHandNum" :step="1" :min="0"
				:max="canBuyNum"></tui-numberbox>
		</view>

		<view class="cell">
			<view class="label" style="width: 300rpx;">服务费（元）{{severRatio*100}}%</view>
			<view class="text-right text-gray flex-sub">
				{{severPay}}
			</view>
		</view>

		<view class="cell">
			<view class="label">可用金额</view>
			<view>{{canUseMoney||0}}</view>
		</view>


		<view class="cell">
			<view class="label">应付(元)</view>
			<view>{{payTotal||0}}</view>
		</view>


		<view class="padding-sm pos-b">
			<tui-button :loading="submiting" :disabled="submiting" type="theme" @click="confirmBuy">买入下单</tui-button>
		</view>

	</view>
</template>

<script setup>
import {ref, inject, watch, computed, onMounted, nextTick} from 'vue';
import {onShow} from '@dcloudio/uni-app';

const tui = inject('tui');

import {buyStock, buyStockPz} from '@/api/index.js';
import {getMarketCode, getShortCode, getAllCode, manyAccMul, manyAccAdd, manyAccAdd1} from '@/utils/stock.js';
import {getUserPriceAll} from '@/api/user.js';

import {useUserStore} from '@/store';
const userStore = useUserStore();

const props = defineProps({
	stockData: {
		type: Object,
		default: () => {}
	},
	code: {
		type: String,
		default: ''
	}
});

const emits = defineEmits(['confirm']);

const handNum = ref(0);
const level = ref(1);
const levers = ref([1]);
const turnover = ref(0);
const turnovers = ref([{
		name: '1/4',
		num: 0.25
	},
	{
		name: '1/3',
		num: 0.33
	},
	{
		name: '1/2',
		num: 0.5
	},
	{
		name: '全仓',
		num: 1
	},
]);
const canBuyNum = ref(0);
const canUseMoney = ref(0);
const yinhuaRatio = ref(0);
const severRatio = ref(0);
const price = ref('');
const submiting = ref(false);
const is_pz = ref(0);
const sysConfigObj = ref({});
const allMaybe = ref([]);

onShow(() => {
	if (uni.getStorageSync('sysConfig')) {
		sysConfigObj.value = uni.getStorageSync('sysConfig');
	}
});

const actualPrice = computed(() => { //实际成交价格,如果开启委托成交价格为输入价格，未开启为市场价格
	return sysConfigObj.value.is_weituo == 1 ? (price.value) : (props.stockData?.['f43'] / 100)
});

const marketCode = computed(() => {
	return getMarketCode(props.code)
});

const totalMoeny = computed(() => { //计算市值
	return manyAccMul(handNum.value, actualPrice.value, level.value, 100)
});

const severPay = computed(() => { //服务费
	return manyAccMul(totalMoeny.value, severRatio.value)
});

const yinHua = computed(() => { //印花税
	return parseInt(0)
});

const payTotal = computed(() => { //应付多少钱 市值+服务费+印花税
	return manyAccAdd(totalMoeny.value, severPay.value, yinHua.value)
});

watch(() => handNum.value, (newValue, oldValue) => {
	if (allMaybe.value) {
		let happen = allMaybe.value.find(v => v.num == newValue)
		if (happen) {
			level.value = happen.level;
			turnover.value = happen.turnover
		} else {
			turnover.value = (newValue / canBuyNum.value).toFixed(2)
		}
	}
});

watch(() => actualPrice.value, (newValue, oldValue) => {
	if (newValue && (newValue != oldValue)) {
		cacleHandNum()
	}
})

onMounted(() => {
	userStore.syncUserInfo().then(user => {
		yinhuaRatio.value = sysConfigObj.value.yh_fee
		severRatio.value = user.is_pz ? sysConfigObj.value.pz_pzsxf : sysConfigObj.value.mai_fee
		canUseMoney.value = user.balance
		// 获取配置模块  是否开启了配资
		is_pz.value = user.is_pz
		price.value = props.stockData?.['f43'] / 100 || '--'
		// 这边就要计算出出可以购买多少手
		// 现价
		let xj = props.stockData?.['f43'] / 100
		// 如果是配资 则需要计算出最大的手数
		let fwfee = parseFloat(sysConfigObj.value.mai_fee) + 1
		let maxshoushu = (parseFloat(canUseMoney.value) / fwfee) / (xj * 100)
		canBuyNum.value = parseInt(maxshoushu)
	})
});

const confirmBuy = () => {
	if (handNum.value == 0 || handNum.value == '') {
		uni.showToast({
			icon: 'none',
			title: '请输入正确的手数'
		})
		return
	}
	emits('confirm', {
		title: props.stockData?.['f58'],
		price: actualPrice.value,
		number: handNum.value * 100,
		total: payTotal.value,
		method: 'buy'
	})
}

const changePrice = (e) => {
	price.value = e.value
}

const changeHandNum = (e) => {
	if (canBuyNum.value <= 0) {
		return
	}
	handNum.value = e.value
}

const cacleHandNum = (newValue) => {
	let allMaybeV = [] //预设所有可能性；
	turnovers.value.forEach((v, tIndex) => {
		levers.value.forEach((v2, lIndex) => {
			let temp = {
				num: parseInt(canBuyNum.value * v.num * v2),
				level: v2,
				turnover: v.num
			}
			allMaybeV.push(temp)
		})
	})
	allMaybe.value = allMaybeV
}

const buy = () => {
	if (handNum.value== 0 || handNum.value == '') {
		tui.toast('请输入正确的手数')
		return
	}
	if (parseFloat(totalMoeny.value) <= 0) {
		return
	}
	submiting.value = true
	let postData = {
		code: getShortCode(props.code),
		allMoney: manyAccAdd(severPay.value, yinHua.value), //综合费用 服务费加印花
		allcode: getAllCode(props.code), //
		buyprice: actualPrice.value, //买入价
		canBuy: handNum.value, //手数
		cityValue: totalMoeny.value, //市值
		is_auto_money: 1, //自动续费设置:0=否,1=是
		is_buy: 1,
		is_sell: 0,
		losePrice: '', //止损价
		money: payTotal.value,
		multiplying: level.value, //倍率，
		number: handNum.value * 100, //购买股数量
		profitPrice: '', //止盈价
		recommendnum: totalMoeny.value,
		strategy_id: getAllCode(props.code), //股票全code 比如 sz300533 带字母
		title: props.stockData?.['f58'],
		status: 1,
		jiami: 1
	}
	// 判断是配资模块  还是普通交易模块
	if (is_pz.value > 0) {
		// 判断倍数是否选中 
		// 配资
		buyStockPz(postData).then(res => {
			tui.modal(null, res.msg, false, () => {
				submiting.value = false
				if (res.code == 1) {
					uni.redirectTo({
						url: sysConfigObj.value.is_weituo == 1 ? '/pages/ucenter/entrust' :
							'/pages/ucenter/holding-pz'
					})
				}
			})
		})
	} else {
		buyStock(postData).then(res => {
			tui.modal(null, res.msg, false, () => {
				submiting.value = false
				if (res.code == 1) {
					uni.redirectTo({
						url: sysConfigObj.value.is_weituo == 1 ? '/pages/ucenter/entrust' :
							'/pages/ucenter/holding'
					})
				}
			})
		})
	}
}

const chooseNum = (val, type) => {
	if (canBuyNum.value <= 0) {
		return
	}
	turnover.value = val;
	nextTick(() => {
		handNum.value = parseInt(canBuyNum.value * turnover.value * level.value)
	})
}

const choosemuilty = (num, name) => {
	if (canBuyNum.value <= 0) {
		return
	}
	if (handNum.value <= 0) {
		return
	}
	level.value = num
	// 重新计算一边 
	let xj = props.stockData?.['f43'] / 100
	let fwfee = parseFloat(sysConfigObj.value.mai_fee) + 1
	let maxshoushu = (parseFloat(canUseMoney.value) / fwfee) / (xj * 100)
	canBuyNum.value = parseInt(maxshoushu / num)
	if (handNum.value > canBuyNum.value) {
		return
	}
	level.value = num
}

defineExpose({buy});
</script>
<style lang="scss" scoped>
	// @import 'common.scss';
	
	.boxshow{
			box-shadow: 0 0rpx 16rpx rgba(0, 0, 0, 0.14);
			border-radius: 16rpx;background: #fff;
		}
		.cell{
			@extend .boxshow;
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 20rpx;
			margin:16rpx 20rpx;
			font-size: 26rpx;
			
	    .sign{width: 36rpx;height: 24rpx;margin-right: 6rpx;}
			
			.label{
				width: 140rpx;
				color: #000000;
				font-size: 32rpx;
				font-weight: 400;
				font-family: PingFangSC, PingFang SC;
			}
			
			.tag{
				font-size: 20rpx;
				padding: 4rpx 20rpx;background: #f5f4f6;border-radius: 4rpx;
				margin: 10rpx 10rpx;
				&.active{
					background: #fff0ea;color:#ff5f25;
				}
			}
		}
		.pos-b{
			position: fixed;left: 0;box-sizing: border-box;
			width: 100%;bottom: 0; z-index: 99;
		}

	.cell {
		box-shadow: none !important;
		border-radius: 0 !important;
		border-bottom: 1px solid #e8e8e8 !important;
		background: #fff !important;
	}
</style>